package com.jumper.property.comparer.core.pool;

import java.util.concurrent.*;

/**
 * 异步执行线程池
 */
public class ThreadPool {
    /**
     * 核心线程数
     */
    private static final int CORE_SIZE = 1;
    /**
     * 线程池大小
     */
    private static final int POOL_SIZE = 5;
    /**
     * 活跃秒数
     */
    private static final long KEEPALIVE = 30L;
    /**
     * 线程队列大小
     */
    private static final int QUEUE_SIZE = 2000;

    /**
     * 初始化一个线程池
     */
    private volatile static ThreadPoolExecutor EXECUTOR = null;

    /**
     * 初始化线程池
     */
    private static synchronized void initThreadPool() {
        if (EXECUTOR == null) {
            EXECUTOR = new ThreadPoolExecutor(
                    CORE_SIZE,
                    POOL_SIZE,
                    KEEPALIVE,
                    TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(QUEUE_SIZE),
                    new ThreadPoolExecutor.CallerRunsPolicy()
            );
        }
    }

    /**
     * 异步执行一个任务
     */
    public static void execute(Runnable command) {
        if (EXECUTOR == null) {
            initThreadPool();
        }
        EXECUTOR.execute(command);
    }

    /**
     * 异步执行一个任务 返回future
     */
    public static <V> Future<V> submit(Callable<V> callable) {
        if (EXECUTOR == null) {
            initThreadPool();
        }
        return EXECUTOR.submit(callable);
    }
}
